<?php

namespace app\controllers\h5;

use app\controllers\h5\base\H5Controller;
use app\models\order\Order;
use app\models\order\OrderItem;
use app\models\product\Product;
use app\models\product\ProductArea;
use app\models\product\ProductAreaList;
use app\models\QueueRepeat;
use app\models\SetUserUp;
use app\models\user\User;
use app\models\user\UserCart as Model;
use app\models\user\UserLevel;

/**
 * Class CartController
 * @package app\controllers\h5
 */
class CartController extends H5Controller
{
    // 处理复购排队
    private function _queue()
    {
        // 是否超限
        $set = SetUserUp::getLastOne();
        $done = (int) QueueRepeat::find()
            ->where(['status' => 2])
            ->andWhere(['user_id' => $this->user->id])
            ->count();
        if ($done >= $set->repeat_num) {
            return '您已经领取过' . $done . '次了, 最多只能领取' . $set->repeat_num . '次!';
        }

        // 时间限制
        // A:第一台，第二台，是身份确定后的48小时内，可获得，超过时间失效
        // B: 第三台：是72小时内，超过时间失效
        $time = User::find()
            ->where(['id' => $this->user->id])
            ->select(['create_time'])
            ->scalar();
        $time = strtotime($time);
        // var_dump($time);exit;
        if ($done < 2) {
            $time += 3600 * 48;
            $t = time();
            if ($t > $time) {
                return '您已经超过48小时了,不能排队!';
            }
        } else {
            $time += 3600 * 72;
            $t = time();
            if ($t > $time) {
                return '您已经超过72小时了,不能排队!';
            }
        }

    }

    public function actionCheckRepeat()
    {
        $id = $this->post('id');

        $user = User::findOne(['id' => $this->user->id]);

        // 复购
        if (ProductArea::checkRepeat($id)) {
            if ($user->level <= 0) {
                return $this->fail('您还没有报单,不能复购!');
            }

            $err = $this->_queue();
            if ($err) {
                return $this->fail($err);
            }
        }


        // 报单处理重复购买
        // if (ProductArea::checkReport($id)) {
        //
        //     // 根据身份等级与产品价格处理[则不判断订单]
        //     // $product = Product::findOne(['id' => $id]);
        //     // $price = $product->price;
        //
        //
        //     // 根据订单处理[后台调整的等级, 则可以下单]
        //     $order_ids = Order::find()
        //         ->where(['user_id' => $this->user->id])
        //         ->andWhere(['!=', 'status', Order::$statusMapping['NON_PAYMENT']])
        //         ->andWhere(['!=', 'status', Order::$statusMapping['CANCEL']])
        //         ->andWhere(['!=', 'status', Order::$statusMapping['DELETE']])
        //         ->andWhere(['!=', 'status', Order::$statusMapping['REFUND']])
        //         ->select(['id'])
        //         ->column();
        //
        //     // var_dump($order_ids);exit;
        //
        //
        //     $product_ids = OrderItem::find()
        //         ->where(['order_id' => $order_ids])
        //         ->select(['product_id'])
        //         ->column();
        //
        //     // var_dump($id, $product_ids);exit;
        //
        //
        //     if (in_array($id, $product_ids)) {
        //         return $this->fail('您已经购买过该产品,不能重复报单!');
        //     }
        // }

        return $this->success();
    }

    public function actionAddCart()
    {
        $user_id = $this->user->id;
        $product_id = $this->post('product_id');
        $quantity = intval($this->post('quantity', 1));
        $price = floatval($this->post('price'));
        $score_cost = floatval($this->post('score_cost'));

        if (ProductArea::checkRepeat($product_id)) {
            $err = $this->_queue();
            if ($err) {
                return $this->fail($err);
            }
        }

        // 84000不能添加到购物车
        // if (ProductArea::checkB84000($product_id)) {
        //     return $this->fail('请直接购买!');
        // }

        // 报单区不能加入购物车
        if (ProductAreaList::checkInArea($product_id, Product::$areaMap['REPORT'])) {
            // $p = Product::findOne(['id' => $product_id]);
            // $set = SetUserUp::getLastOne();
            // if ($p->price == $set->svip1) {
            //     return $this->fail('该商品不能加入购物车,请直接购买!');
            // }
            return $this->fail('报单商品不能加入购物车,请直接购买!');
        }

        if (ProductAreaList::checkInArea($product_id, Product::$areaMap['MONEY'])) {
            // $p = Product::findOne(['id' => $product_id]);
            // $set = SetUserUp::getLastOne();
            // if ($p->price == $set->svip1) {
            //     return $this->fail('该商品不能加入购物车,请直接购买!');
            // }
            return $this->fail('银行系统不能加入购物车,请直接购买!');
        }

        // sku
        $product_sku_id = $this->post('product_sku_id', 0);
        $selected_sku_value = json_encode($this->post('selected_sku_value', []));
        $selected_sku_text = json_encode($this->post('selected_sku_text', []));

        if ($product_sku_id) {
            $model = Model::findOne(['user_id' => $user_id, 'product_id' => $product_id, 'product_sku_id' => $product_sku_id]);
        } else {
            $model = Model::findOne(['user_id' => $user_id, 'product_id' => $product_id]);
        }
        if ($model) {
            $model->quantity += $quantity;
        } else {
            $model = new Model();
            $model->product_id = $product_id;
            $model->user_id = $user_id;
            $model->quantity = $quantity;
            $model->price = $price;
            $model->score_cost = $score_cost;
            if ($product_sku_id) {
                $model->product_sku_id = $product_sku_id;
                $model->selected_sku_value = $selected_sku_value;
                $model->selected_sku_text = $selected_sku_text;
            }
        }

        if ($model->save()) {
            return $this->success('添加成功');
        }

        return $this->fail();
    }

    public function actionListTotal()
    {
        // 小程序首页需要获取购物车数量,
        // 如果没有登录, 则返回空
        if (!$this->user) {
            return $this->successEncode([]);
        }

        $list = Model::find()
            ->where(['user_id' => $this->user->id])
            // ->with(['product', 'product.mainImage', 'product.area'])
            ->with([
                'product', 'product.mainImage', 'product.area', 'product.area.name',
                'sku',
                // 供应商名称
                'product.supplierName'
            ])
            ->orderBy(['id' => SORT_DESC])
            ->asArray()
            ->all();

        // var_dump($list);exit;

        return $this->successEncode($list);
    }
    public function actionList()
    {
        // 小程序首页需要获取购物车数量,
        // 如果没有登录, 则返回空
        if (!$this->user) {
            return $this->successEncode([]);
        }

        $list = Model::find()
            ->where(['user_id' => $this->user->id])
            // ->with(['product', 'product.mainImage', 'product.area'])
            ->with([
                'product', 'product.mainImage', 'product.area', 'product.area.name',
                'sku',
                // 供应商名称
                'product.supplierName'
            ])
            ->orderBy(['id' => SORT_DESC])
            ->asArray()
            ->all();

        // var_dump($list);exit;

        // 复购价格显示
        foreach ($list as &$item) {
            // var_dump($item);exit;
            if ($item['product']) {
                $item['product']['price'] = Product::getPriceByLevel($item['product']['id'], $this->user->id, $item['product']['price']);

                $item['price'] = $item['product']['price'];
            }

            // var_dump($item['product']);exit;
        }

        return $this->successEncode($list);
    }

    public function actionAllSelected()
    {
        // boolean to int
        $selected = intval($this->post('selected'));

        $result = Model::updateAll(['selected' => $selected], ['user_id' => $this->user->id]);
        if (false !== $result) {
            return $this->success();
        }

        return $this->fail();
    }

    public function actionItemSelected()
    {
        // boolean to int
        $selected = intval($this->post('selected'));

        $id = $this->post('id');

        $model = Model::findOne(['id' => $id, 'user_id' => $this->user->id]);
        if ($model) {
            $model->selected = $selected;
            if ($model->save()) {
                return $this->success();
            }
        }

        return $this->fail();
    }

    public function actionIncrement()
    {
        $id = $this->post('id');

        $model = Model::findOne(['id' => $id, 'user_id' => $this->user->id]);
        if ($model) {
            $model->quantity += 1;
            $model->selected = 1;
            if ($model->save()) {
                return $this->success();
            }
        }

        return $this->fail();
    }

    public function actionDecrement()
    {
        $id = $this->post('id');

        $model = Model::findOne(['id' => $id, 'user_id' => $this->user->id]);
        if ($model) {
            if ($model->quantity > 0) {
                $model->quantity -= 1;
                if ($model->quantity > 0) {
                    $model->selected = 1;
                }
            }
            if ($model->save()) {
                return $this->success();
            }
        }

        return $this->fail();
    }

    public function actionDeleteCart()
    {
        $result = Model::deleteAll(['user_id' => $this->user->id, 'selected' => 1]);
        if ($result !== false) {
            return $this->success();
        }

        return $this->fail();
    }

    public function actionClearCart()
    {
        $result = Model::deleteAll(['user_id' => $this->user->id]);
        if ($result !== false) {
            return $this->success();
        }

        return $this->fail();
    }

    public function actionGetCartQuantity()
    {
        $count = Model::find()
            ->where(['user_id' => $this->user->id, 'selected' => 1])
            ->sum('quantity');

        return $this->success($count);
    }

    public function actionChangeQuantity()
    {
        $id = $this->post('id');
        $quantity = $this->post('quantity');

        $quantity = intval($quantity);
        if ($quantity <= 0) {
            return $this->fail('数量错误');
        }

        $model = Model::findOne(['id' => $id]);
        if ($model) {
            $model->quantity = $quantity;
            $model->save();

            return $this->success();
        }
    }
}